<?php


namespace app\api\model;
use think\facade\Log;
use think\Model;
use think\Db;
class Merchant extends Model
{
    protected $name = 'merchant';

    public function index($params,$where){
        $terminal=$params['terminal'];
        $sql=self::alias('m')->where($where)->field('m.id,avatar,m.name,terminal,category,sub_category,week,start_time,end_time,profile,phone_number,telephone,is_pause');
        if($params['keyword']){
            $sql=$sql->leftJoin('category c','c.id=m.category');
        }
        if($params['sub_category']){
            $sub_category=explode(',',$params['sub_category']);
            $sql=$sql->where(function ($query) use($sub_category){
                foreach ($sub_category as $key=>$val){
                    if($key==0){
                        $query=$query->where('find_in_set(:category_id,sub_category)',['category_id'=>$val]);
                    }else{
                        $query->whereOr('find_in_set(:category_id,sub_category)',['category_id'=>$val]);
                    }
                }
            });
        }
        $sql=$sql->when($params['terminal'],function ($query) use($terminal){
            $query->whereIn('terminal',$terminal);
        });

        $res=$sql->select()->toArray();
//        echo $sql->getLastSql();die;
        $data['result']=$res;
        $data['total']=$this->getCount($params,$where);
        $data['pageCount']=ceil($data['total']/$params['pageSize']);
        return $data;
    }

    public function getCount($params,$where){
        $terminal=$params['terminal'];
        $sql=self::alias('m')->where($where);
        if($params['keyword']){
            $sql=$sql->leftJoin('category c','c.id=m.category');
        }
        if($params['sub_category']){
            $sub_category=explode(',',$params['sub_category']);
            $sql=$sql->where(function ($query) use($sub_category){
                foreach ($sub_category as $key=>$val){
                    if($key==0){
                        $query=$query->where('find_in_set(:category_id,sub_category)',['category_id'=>$val]);
                    }else{
                        $query->whereOr('find_in_set(:category_id,sub_category)',['category_id'=>$val]);
                    }
                }
            });
        }
        $sql=$sql->when($params['terminal'],function ($query) use($terminal){
            $query->whereIn('terminal',$terminal);
        });

        return $sql->count();
    }

    public function info($id){
        $res=self::where(['id'=>$id])->field('name,email,country,category,sub_category,airport,terminal,phone_number,images,telephone,address,address_link,week,start_time,end_time,profile,avatar,category,sub_category,is_pause,status,header_image')->find();
        if(empty($res)) return false;
        $info=$res->toArray();
        if($info['status']==-1) return false;
        $airportInfo=Airport::where(['id'=>$info['airport']])->field('name,terminal')->find();
        $info['airport_name']=$airportInfo['name'];
        $info['terminal_list']=json_decode($airportInfo['terminal'],true);
        $areaInfo=Area::where(['id'=>$info['country']])->field('name,timezone,abbreviation,flag,phone_code')->find();
        $country_timezone=$areaInfo['timezone'];
        $info['open_status']=merchantStatus($country_timezone,$info);
        $info['country_name']=$areaInfo['name'];
        $info['abbreviation']=$areaInfo['abbreviation'];
        $info['country_phone_code']=$areaInfo['phone_code'];
        if($areaInfo['flag']){
            $info['flag']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($areaInfo['flag']);
        }else{
            $info['flag']='';
        }
        if($info['start_time']){
            $info['start_time']=substr($info['start_time'],0,strripos($info['start_time'],':'));
            $info['end_time']=substr($info['end_time'],0,strripos($info['end_time'],':'));
        }
        //处理payment
        $payment_ids=Db::table(config('database.prefix').'merchant_payment')->where(['merchant_id'=>$id])->field('payment_id')->select();
        $payment_ids=array_column($payment_ids,'payment_id');
//        if(count($payment_ids)>=3){
//            $payments=Db::table(config('database.prefix').'payment')->where('id','in',$payment_ids)->field('name')->limit(3)->order('id','desc')->select();
//        }else{
//            if($payment_ids){
//                $payments=Db::table(config('database.prefix').'payment')->field('name')->limit(3)->orderRaw('field(id,'.implode(',',$payment_ids).') desc')->select();
//            }else{
//                $payments=[];
//                $all_payments=Db::table(config('database.prefix').'payment')->field('name')->order('id','desc')->select();
//            }
//        }
//
//        if($payment_ids) $all_payments=Db::table(config('database.prefix').'payment')->field('name')->orderRaw('field(id,'.implode(',',$payment_ids).') desc')->select();
        if($payment_ids){
            $all_payments=Db::table(config('database.prefix').'payment')->where(['status'=>1,'is_delete'=>0])->field('id,icon')->orderRaw('field(id,'.implode(',',$payment_ids).') desc')->select();
        }else{
            $all_payments=Db::table(config('database.prefix').'payment')->where(['status'=>1,'is_delete'=>0])->field('id,icon')->order('id','desc')->select();
        }
        foreach ($all_payments as $key=>$val){
            if($key+1>count($payment_ids)){
                $all_payments[$key]['is_belong']=0;
            }else{
                $all_payments[$key]['is_belong']=1;
            }
            $all_payments[$key]['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($val['icon']);
        }
//        $info['payments']=$payments;
        $info['more_payments']=$all_payments;

        $features=Db::table(config('database.prefix').'merchant_feature')->alias('mf')
            ->join(config('database.prefix').'feature f','f.id=mf.feature_id')
            ->field('f.id,f.name,f.icon,f.select_icon')
//            ->where(['f.status'=>1,'f.is_delete'=>0,'mf.merchant_id'=>$id])
            ->where(['f.status'=>1,'mf.merchant_id'=>$id])
            ->select();
        if($features){
            foreach ($features as &$value){
                if($value['icon']){
                    $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['icon']);
                }else{
                    $value['icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.feature_icon_default');
                }
                if($value['select_icon']){
                    $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_file_path($value['select_icon']);
                }else{
                    $value['select_icon']=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.config('data.feature_select_icon_default');
                }
            }
        }

        $info['features']=$features;


        return $info;
    }

    /**
     * @param $data
     * @param int $type 1：创建2：修改信息
     * @return bool
     */
    public function complete($data,$type=1){
        //获取洲
        $data['continent']=Area::where(['id'=>$data['country'],'type'=>'country'])->value('parent_id');
//        $type=$data['type'];
//        unset($data['type']);
        Db::startTrans();
        try {
            $features=[];
            $payments=[];
            if(isset($data['feature']) && $data['feature']){
                $features=explode(',',$data['feature']);
            }
            unset($data['feature']);

            if(isset($data['payment']) && $data['payment']){
                $payments=explode(',',$data['payment']);
            }
            unset($data['payment']);
            if($type==1){
                $data['id']=self::insertGetId($data);
            }else{
                self::update($data);
            }
            if($features){
                $feature_data=[];
                foreach ($features as $key=>$feature){
                    $feature_data[$key]['merchant_id']=$data['id'];
                    $feature_data[$key]['feature_id']=$feature;
                }
                //先删除再增加
                Db::table(config('database.prefix').'merchant_feature')->where(['merchant_id'=>$data['id']])->delete();
                Db::table(config('database.prefix').'merchant_feature')->insertAll($feature_data);
            }
            if($payments){
                $payment_data=[];
                foreach ($payments as $key=>$payment){
                    $payment_data[$key]['merchant_id']=$data['id'];
                    $payment_data[$key]['payment_id']=$payment;
                }
                Db::table(config('database.prefix').'merchant_payment')->where(['merchant_id'=>$data['id']])->delete();
                Db::table(config('database.prefix').'merchant_payment')->insertAll($payment_data);
            }

            //商户数+1
            if($type==1){
                Db::table(config('database.prefix').'airport')->where('id',$data['airport'])->setInc('merchant');
            }
            // 提交事务
            Db::commit();
            return $data['id'];
        } catch (\Exception $e) {
            // 回滚事务
            Log::error('接口处理报错,错误信息：'.$e->getMessage().'错误文件：'.$e->getFile().'错误行数：'.$e->getLine());
            Db::rollback();
            return false;
        }

    }

    public function getInfo($where,$field){
        return self::where($where)->field($field)->find()->toArray();
    }

    public function getTitle($keyword){
        return self::whereLike('name',$keyword.'%')->distinct(true)->field('name')->limit(20)->select()->toArray();
    }
}